<template>
  <div id="app">
    <div class="content">
      <h1>学生管理系统</h1>
      <div class="ipt">
        <input type="button" v-if="isShow" @click="isShow = false" value="添加学生">
        <div v-else class="add">
          <input type="button" @click="addLi" value="确认添加">
          <input type="button" @click="isShow = true" value="取消添加">
          <input type="text" v-model="tabList.name" placeholder="学生名字">
          <input type="text" v-model.number="tabList.age" placeholder="学生年龄">
          <input type="text" v-model.number="tabList.grades" placeholder="学生成绩">
        </div>
      </div>
      <div class="align">
        <input type="button" @click="sortList('age')" value="按年龄排">
        <input type="button" @click="sortList('grades')" value="按成绩排">
      </div>
      <table border="1" style="border-collapse: collapse;" cellpadding="10" align="center">
        <thead>
          <tr>
            <th width="150">名字</th>
            <th width="150">年龄</th>
            <th width="150">成绩</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="item in message" :key="item.id">
            <td>{{ item.name }}</td>
            <td>{{ item.age }}</td>
            <td>{{ item.grades }}</td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script>
export default {
  name: 'app',
  data() {
    return {
      isShow: true,
      tabList: {},
      message: [
        {
          id: 1,
          name: '张三',
          age: 18,
          grades: 88
        }
      ],
    }
  },
  methods: {
    addLi() {
      if (this.tabList.name === undefined || this.tabList.age === undefined || this.tabList.grades === undefined ||
        this.tabList.name === "" || this.tabList.age === "" || this.tabList.grades === "") {
        return alert("请输入完整的学生信息！")
      }
      this.tabList.id = Math.random() + ''
      this.message.push(this.tabList)
      this.tabList = {}
    },
    sortList(key) {
      this.message.sort((a, b) => a[key] - b[key])
    }
  }
}
</script>

<style scoped>
h3 {
  margin: 40px 0 0;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: inline-block;
  margin: 0 10px;
}

a {
  color: #42b983;
}

.align {
  margin: 10px 0;
}
</style>
